package com.newegg.datafeed.adserving.api.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.newegg.datafeed.adserving.api.annotation.AccessRequired;
import com.newegg.datafeed.adserving.model.UserType;
import com.newegg.datafeed.adserving.util.TokenUtil;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
	
	@Autowired
	TokenUtil tokenUtil;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod){
			String token = request.getHeader("token");
			String user = request.getHeader("user");
			String role = request.getHeader("role");
			HandlerMethod handlerMethod = (HandlerMethod) handler;
	        Method method = handlerMethod.getMethod();
	        AccessRequired annotation = method.getAnnotation(AccessRequired.class);
	        if(annotation == null){
	        	return HandlerInterceptor.super.preHandle(request, response, handler);
	        }else if(StringUtils.isEmpty(token) || StringUtils.isEmpty(user) || StringUtils.isEmpty(role)){
	        	response.sendError(401, "not login");
	        	return false; 
	        }else{
	        	UserType[] types = annotation.role();
	 	        for (UserType userType : types) {
	 	        	if(userType.name().equals(role) && authentication(token, user, role)){
	 	        		return HandlerInterceptor.super.preHandle(request, response, handler);
	 	        	}
	 			}
	 	        response.sendError(401, "authentication failed");
	 	        return false;
	        }
		}else{
			return HandlerInterceptor.super.preHandle(request, response, handler);
		}
	}

	private boolean authentication(String token, String user, String role) {
		String token2 = tokenUtil.getToken(role + ":" + user);
		return token2.equals(token);
	}
}
